var app = getApp();
var url = app.url;
var pageNumber = 1;
Page({
  data: {
    showLoading: true, // 等待动画
    menu: '',
    chidx: 0,// 选中地区下标
    opType: '',// 1==开，0==关
    list:[],
    keyword:'',
    teamList:[],
    treamId:wx.getStorageSync('treamId') || '',
    teamName:'',
    dataNum:0,
    faultDescription:'',
    startTime:'',
    endTime:'',
    filterShow:false,
    // gzList: ['全部','路灯不亮', '灯杆损坏倾斜', '线缆外露损坏', '灯杆门缺损', '附近成片熄灯',],
    gzList: [
      {value:'全部',checked:false},
      {value:'单灯不亮',checked:false},
      {value:'线路故障',checked:false}, 
      {value:'控制箱故障',checked:false}, 
      {value:'灯杆门缺损',checked:false}, 
      {value:'灯杆缺陷',checked:false},
      {value:'乱挂广告牌',checked:false}, 
      {value:'紧急突发故障',checked:false}, 
      {value:'其他故障隐患',checked:false}, 
      {value:'日常巡检设备',checked:false}, 
    ],
    reportTypeShow:false,
    reportTypeList:[
      {name:'全部',value:'',checked:false},
      // {name:'外部上报',value:'0',checked:false},
      {name:'路灯上报',value:'1',checked:false},
      {name:'配电箱上报',value:'3',checked:false},
      {name:'自定义上报',value:'2',checked:false},
    ],
    reportType:'',
    personList:[],
    personName:'',
    teamShow:false,
    userId:'',
    localUserId:wx.getStorageSync('userId'),
    gzShow:false,
    importList:['95598','12345','住建工单','城市交办函'],
    dataSourceList:['全部','86881114','12345','95598','交警','住建工单','城市交办函','其他'],
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    console.log(options)
    pageNumber = 1;
    if (options.keyword)this.setData({ keyword: options.keyword })
    this.getTeamList()
  },
  onShow: function () {
    // 页面显示
    pageNumber = 1;
    this.checkLogin()
    var name = wx.getStorageSync('userName')
    if(name){
      this.getUserMeters(true)
    }
    
    
  },
  onReady: function () {
    // 页面渲染完成
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  onPullDownRefresh: function () { 
    pageNumber = 1; 
    this.getUserMeters(true)
  },
  onShareAppMessage: function () {

  },
  initTeamChoose(){
    let teamList = this.data.teamList
    teamList.forEach((item,index)=>{
      item.checked = String(this.data.treamId).includes(item.id.toString())
    })
    this.setData({teamList})
  },
  checkLogin: function () {
    var name = wx.getStorageSync('userName')
    if (name == '' || name == null) {
      wx.showModal({
        title: '提示',
        content: "用户未登录",
        confirmText: '去登录',
        showCancel: false,
        success: function () {
          wx.navigateTo({
            url: '../login/login',
          })
        }
      })
    }
  },
  getUserMeters (reload) {
    var that = this;
    var list = this.data.list;
    var header = { 'content-type': 'application/x-www-form-urlencoded' }
    let {dataSource,reportType} = this.data;
    var params = { 
      // serName: wx.getStorageSync('userName'), 
      pageSize: 20, pageNumber: pageNumber, 
      deptId: wx.getStorageSync('deptId'), 
      address: that.data.keyword,
      treamId: this.data.personName?'':that.data.treamId,
      faultDescription: that.data.faultDescription == '全部'?'':that.data.faultDescription,
      startTime: that.data.startTime,
      endTime: that.data.endTime,
      userName: this.data.personName,
      userId: this.data.userId,
      dataSource,reportType
    }
  
    console.log(params)
    var encodingStr = app.ecbEncrypto(params);
    console.log(encodingStr);
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: url + '/api/account/getSysExceptionReportList.htm',
      data: encodingStr,
      method: 'POST',
      header: header,
      success: (res) => {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr);
        rest.result.content.forEach((item)=>{
          item.createTime = js_date_time(item.createTime);
          // item.createTime = item.createTime.substr(0,10);
          item.isOrange = this.data.importList.includes(item.dataSource)
        })
        if (rest.isSuccess == 0) {
          
          // for (var i in rest.result.content){
          //   list.push(rest.result.content[i])
          // }
          if (!reload){
            list = list.concat(rest.result.content);
          }else{
            list = rest.result.content
          }
          

          that.setData({ list: list,dataNum:rest.result.totalElements })
          
        } else {
          wx.showModal({
            title: '提示',
            content: rest.errorMsg,
            showCancel: false
          })
        }
        console.log(rest)
      },
      complete: function () {
        wx.stopPullDownRefresh()
        that.setData({ showLoading: false })
        wx.hideLoading();
      }
    })
  },
  // 跳转
  showSzByName: function (e) {
    var idx = e.currentTarget.dataset.idx
    var list = this.data.fzList
    wx.setStorageSync("area" + idx, list[idx])// 缓存数据
    wx.navigateTo({
      url: '../control/zdarea?idx=' + idx,
    })
  },
  callPhone:function (e){
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone, 
      success: function () {
        
      },
      fail: function () {
        
      }
    });
  },
  bindToDetail: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: 'reportDetail?id=' + id,
    })
  },
  tolower:function(){
    pageNumber++;
    this.getUserMeters();
  },
  toSearch(){
    console.log(this.data.keyword)
    pageNumber = 1; 
    this.getUserMeters(true)
    this.setData({
      filterShow:false,
      teamShow:false,
      gzShow:false,
      reportTypeShow:false
    })
  },
  clearSearch(){
    this.setData({
      // keyword: '',
      // treamId: '',
      // faultDescription:'',
      startTime:'',
      endTime:'',
      // teamName:'',
    })
  },
  inputgetKeyword(e){
    this.setData({
      keyword: e.detail.value
    })
  },
  getTeamList(){
    var that = this;
    var params = {
      pageNumber: 1,
      pageSize: 10000,
      deptid: wx.getStorageSync('deptId'),
      type: 1,
    }
    var paramsCode = app.ecbEncrypto(params)
    wx.request({
      url: app.url + '/web/sysTream/getList.htm',
      data: paramsCode,
      method: 'POST',
      success:  (res)=> {
        var decodingStr = app.ecbDecrypto(res.data);
        var rest = JSON.parse(decodingStr)
        console.log(rest)
        if (rest.isSuccess == 0) {
          var list = rest.result.content
          that.setData({
            teamList: list,
          })
          this.initTeamChoose()
        }
      },
      complete: function () {

      }
    })
  },
  teamChange(event){
    const index = event.detail.value;
    const obj = this.data.teamList[index];
    this.setData({treamId:obj.id,teamName:obj.name})
    this.toSearch()
  },
  startTimeChange(event){
    this.setData({startTime:event.detail.value})
  },
  endTimeChange(event){
    this.setData({endTime:event.detail.value})
  },
  showFilter(){
    this.setData({filterShow:true})
  },
  inputChange(e) {
    let obj = {};
    obj[e.currentTarget.dataset.key] = e.detail.value
    this.setData(obj)
  },
  desChange(event){
    const index = event.detail.value;
    const value = this.data.gzList[index];
    this.setData({faultDescription:value == '全部'?'':value})
    this.toSearch()
  },
  filterDataSource(event){
    const index = event.detail.value;
    const value = this.data.dataSourceList[index];
    this.setData({dataSource:value == '全部'?'':value})
    this.toSearch()
  },
  checkboxChange:function(e){
    var cboxs = e.detail.value;
    var val = cboxs.toString();
    let teamList = this.data.teamList
    teamList.forEach((item,index)=>{
      item.checked = cboxs == item.id
    })
    this.setData({treamId:val,teamList,personName:''})
    if(cboxs){
      this.getPersonList()
    }else{
      this.setData({personList:[]})
    }
  },
  clearTeam(){
    let teamList = this.data.teamList
    teamList.forEach((item,index)=>{
      item.checked = false
    })
    this.setData({treamId:'',personName:'',personList:[],teamList})
  },
  clearReportType(){
    const list = this.data.reportTypeList;
    list.forEach((item,index)=>{
      item.checked = false
    })
    this.setData({reportType:'',reportTypeList:list})

  },
  getPersonList(){
    var that = this;
    var list = this.data.list;
    var header = { 'content-type': 'application/x-www-form-urlencoded' }
    var params = {
      pageSize: 1000, 
      pageNumber: 1,
      treamId: that.data.treamId,
    }
    console.log(params);
    var encodingStr = app.ecbEncrypto(params);
    console.log(encodingStr);
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: url + '/web/baseAccount/getList2.htm',
      data: encodingStr,
      method: 'POST',
      header: header,
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        console.log(decodingStr)
        var rest = JSON.parse(decodingStr);
        console.log(rest)
        if (rest.isSuccess == 0) {
          that.setData({ personList: rest.result.content,})
        } else {
          wx.showModal({
            title: '提示',
            content: rest.errorMsg,
            showCancel: false
          })
        }
        console.log(rest)
      },
      complete: function () {
        wx.stopPullDownRefresh()
        that.setData({ showLoading: false })
        wx.hideLoading();
      }
    })
  },
  personChange(e){
    const cboxs = e.detail.value
    let personList = this.data.personList
    personList.forEach((item,index)=>{
      item.checked = cboxs == item.loginName
    })
    this.setData({personName:cboxs,personList})
  },
  showTeam(){
    this.setData({teamShow:true})
  },
  showGz(){
    this.setData({gzShow:true})
  },
  showReportType(){
    this.setData({reportTypeShow:true})
  },
  clearGz(){
    let gzList = this.data.gzList
    gzList.forEach((item,index)=>{
      item.checked = false
    })
    this.setData({
      faultDescription:'',
      gzList
    })
  },
  checkboxChangeCom(e){
    const {listname,listkey} = e.currentTarget.dataset;
    var cboxs = e.detail.value;
    var faultItems = this.data[listname];
    console.log(cboxs)
    console.log(faultItems)
    faultItems.forEach((item,index)=>{
      item.checked = cboxs == item.value
    })
    const obj = {};
    obj[listname] = faultItems;
    obj[listkey] = cboxs.toString();
    console.log(obj);
    this.setData(obj);
    console.log(e)
  },
  filterMine(){
    this.clearTeam()
    this.setData({
      userId: this.data.userId?'':wx.getStorageSync('userId')
    })
    this.toSearch()
  }
});


function js_date_time(unixtime) {
  var dateTime = new Date(parseInt(unixtime))
  var year = dateTime.getFullYear();
  var month = (dateTime.getMonth() + 1) < 10 ? "0" + (dateTime.getMonth() + 1) : (dateTime.getMonth() + 1);
  var day = dateTime.getDate() < 10 ? "0" + dateTime.getDate() : dateTime.getDate();
  var hour = dateTime.getHours() < 10 ? "0" + dateTime.getHours() : dateTime.getHours();
  var minute = dateTime.getMinutes() < 10 ? "0" + dateTime.getMinutes() : dateTime.getMinutes();
  var second = dateTime.getSeconds();
  var now = new Date();
  var now_new = Date.parse(now.toDateString());  //typescript转换写法
  var milliseconds = now_new - dateTime;
  var timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
  return timeSpanStr;
}